import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.List;

public class ScoreViewFrame extends JFrame {
    private int examId;
    private int studentId;
    private Exam exam;
    private ExamRecord examRecord;
    private List<Question> questions;
    private List<AnswerRecord> answers;

    // UI组件
    private JLabel examTitleLabel;
    private JLabel scoreLabel;
    private JLabel statusLabel;
    private JLabel timeInfoLabel;
    private JTable detailTable;
    private DefaultTableModel tableModel;
    private JButton closeButton;
    private JButton refreshButton;

    // DAO
    private ExamDAO examDAO;
    private ExamRecordDAO examRecordDAO;
    private QuestionDAO questionDAO;
    private AnswerRecordDAO answerDAO;
    private UserDAO userDAO;

    public ScoreViewFrame(int examId, int studentId) {
        this.examId = examId;
        this.studentId = studentId;
        this.examDAO = new ExamDAO();
        this.examRecordDAO = new ExamRecordDAO();
        this.questionDAO = new QuestionDAO();
        this.answerDAO = new AnswerRecordDAO();
        this.userDAO = new UserDAO();

        loadData();
        initComponents();
        setupLayout();
        setupEvents();
        loadScoreDetails();
    }

    private void loadData() {
        System.out.println("=== 开始加载数据 ===");
        exam = examDAO.getExamById(examId);
        examRecord = examRecordDAO.getExamRecord(examId, studentId);
        questions = questionDAO.getQuestionsByExamId(examId);

        // 调试信息
        System.out.println("Debug - examId: " + examId + ", studentId: " + studentId);
        System.out.println("Debug - exam: " + (exam != null ? exam.getTitle() : "null"));
        System.out.println("Debug - examRecord: "
                + (examRecord != null ? "ID=" + examRecord.getId() + ", totalScore=" + examRecord.getTotalScore()
                        : "null"));
        System.out.println("Debug - questions count: " + (questions != null ? questions.size() : "null"));

        if (examRecord != null) {
            answers = answerDAO.getAnswersByExamRecord(examRecord.getId());
            System.out.println("Debug - answers count: " + (answers != null ? answers.size() : "null"));

            // 详细打印每个答案记录的分数
            if (answers != null) {
                for (AnswerRecord answer : answers) {
                    System.out.println("Debug - Answer Record: questionId=" + answer.getQuestionId() +
                            ", score=" + answer.getScore() + ", answerText=" + answer.getAnswerText());
                }
            }
        } else {
            System.out.println("Debug - examRecord is null, cannot load answers");
        }
        System.out.println("=== 数据加载完成 ===");
    }

    private void refreshData() {
        System.out.println("=== 刷新数据 ===");
        loadData();
        updateBasicInfo();
        loadScoreDetails();
        System.out.println("=== 刷新完成 ===");
    }

    private void initComponents() {
        setTitle("成绩详情 - " + (exam != null ? exam.getTitle() : "考试"));
        setSize(900, 700);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        // 基本信息标签
        examTitleLabel = new JLabel();
        examTitleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));

        scoreLabel = new JLabel();
        scoreLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));

        statusLabel = new JLabel();
        statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));

        timeInfoLabel = new JLabel();
        timeInfoLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));

        // 详细表格
        String[] columnNames = { "题号", "题型", "题目内容", "我的答案", "正确答案", "得分", "满分" };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        detailTable = new JTable(tableModel);
        detailTable.setRowHeight(30);
        detailTable.getColumnModel().getColumn(2).setPreferredWidth(200);
        detailTable.getColumnModel().getColumn(3).setPreferredWidth(150);
        detailTable.getColumnModel().getColumn(4).setPreferredWidth(150);

        closeButton = new JButton("关闭");
        closeButton.setPreferredSize(new Dimension(100, 35));

        refreshButton = new JButton("刷新");
        refreshButton.setPreferredSize(new Dimension(100, 35));
        refreshButton.setBackground(new Color(40, 167, 69));
        refreshButton.setForeground(Color.WHITE);
        refreshButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
    }

    private void setupLayout() {
        setLayout(new BorderLayout());

        // 顶部信息面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(new Color(70, 130, 180));
        topPanel.setPreferredSize(new Dimension(900, 120));
        topPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 考试信息
        JPanel examInfoPanel = new JPanel(new GridLayout(2, 1, 5, 5));
        examInfoPanel.setBackground(new Color(70, 130, 180));
        examInfoPanel.add(examTitleLabel);
        examInfoPanel.add(timeInfoLabel);

        // 成绩信息
        JPanel scorePanel = new JPanel(new GridLayout(2, 1, 5, 5));
        scorePanel.setBackground(new Color(70, 130, 180));
        scorePanel.add(scoreLabel);
        scorePanel.add(statusLabel);

        topPanel.add(examInfoPanel, BorderLayout.CENTER);
        topPanel.add(scorePanel, BorderLayout.EAST);

        // 中间详细表格
        JScrollPane scrollPane = new JScrollPane(detailTable);
        scrollPane.setBorder(BorderFactory.createTitledBorder("答题详情"));

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(refreshButton);
        buttonPanel.add(closeButton);

        add(topPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        // 设置基本信息
        updateBasicInfo();
    }

    private void setupEvents() {
        closeButton.addActionListener(e -> dispose());

        refreshButton.addActionListener(e -> {
            refreshData();
            JOptionPane.showMessageDialog(this, "数据已刷新！", "提示", JOptionPane.INFORMATION_MESSAGE);
        });
    }

    private void updateBasicInfo() {
        if (exam != null) {
            examTitleLabel.setText(exam.getTitle());
            examTitleLabel.setForeground(Color.WHITE);
        }

        if (examRecord != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            // 成绩信息
            double totalScore = examRecord.getTotalScore();
            double maxScore = exam != null ? exam.getTotalScore() : 100;
            scoreLabel.setText(String.format("得分：%.1f / %.1f", totalScore, maxScore));

            // 判断是否及格
            double passScore = exam != null ? exam.getPassScore() : 60;
            if (totalScore >= passScore) {
                scoreLabel.setForeground(new Color(40, 167, 69)); // 绿色
                statusLabel.setText("考试状态：及格");
                statusLabel.setForeground(new Color(40, 167, 69));
            } else {
                scoreLabel.setForeground(new Color(220, 53, 69)); // 红色
                statusLabel.setText("考试状态：不及格");
                statusLabel.setForeground(new Color(220, 53, 69));
            }

            // 时间信息
            StringBuilder timeInfo = new StringBuilder();
            if (examRecord.getStartTime() != null) {
                timeInfo.append("开始时间：").append(sdf.format(examRecord.getStartTime()));
            }
            if (examRecord.getSubmitTime() != null) {
                timeInfo.append("  |  提交时间：").append(sdf.format(examRecord.getSubmitTime()));

                // 计算用时
                long duration = examRecord.getSubmitTime().getTime() - examRecord.getStartTime().getTime();
                long minutes = duration / (1000 * 60);
                long seconds = (duration % (1000 * 60)) / 1000;
                timeInfo.append("  |  用时：").append(minutes).append("分").append(seconds).append("秒");
            }

            timeInfoLabel.setText(timeInfo.toString());
            timeInfoLabel.setForeground(Color.WHITE);
        }
    }

    private void loadScoreDetails() {
        System.out.println("=== 开始加载成绩详情 ===");
        tableModel.setRowCount(0);

        if (questions == null || questions.isEmpty()) {
            System.out.println("Debug - 没有题目数据");
            return;
        }

        for (int i = 0; i < questions.size(); i++) {
            Question question = questions.get(i);

            // 查找对应的答案记录
            AnswerRecord answerRecord = null;
            if (answers != null) {
                for (AnswerRecord answer : answers) {
                    if (answer.getQuestionId() == question.getId()) {
                        answerRecord = answer;
                        break;
                    }
                }
            }

            // 详细调试信息
            System.out.println("Debug - Question " + (i + 1) + " (ID: " + question.getId() + "):");
            System.out.println("  - questionText: " + question.getQuestionText());
            System.out.println("  - questionScore: " + question.getScore());
            System.out.println("  - answerRecord: " + (answerRecord != null ? "found" : "null"));
            if (answerRecord != null) {
                System.out.println("  - answer text: " + answerRecord.getAnswerText());
                System.out.println("  - answer score: " + answerRecord.getScore());
                System.out.println("  - answer ID: " + answerRecord.getId());
                System.out.println("  - examRecordId: " + answerRecord.getExamRecordId());
            }

            // 题目内容（截取显示）
            String questionText = question.getQuestionText();
            if (questionText.length() > 50) {
                questionText = questionText.substring(0, 50) + "...";
            }

            // 我的答案
            String myAnswer = answerRecord != null ? answerRecord.getAnswerText() : "未作答";
            if (myAnswer != null && myAnswer.length() > 30) {
                myAnswer = myAnswer.substring(0, 30) + "...";
            }

            // 正确答案
            String correctAnswer = getCorrectAnswer(question);

            // 得分 - 确保显示最新分数
            double score = answerRecord != null ? answerRecord.getScore() : 0.0;
            System.out.println("  - 最终显示分数: " + score);

            Object[] row = {
                    i + 1,
                    getQuestionTypeText(question.getQuestionType()),
                    questionText,
                    myAnswer,
                    correctAnswer,
                    String.format("%.1f", score),
                    String.format("%.1f", question.getScore())
            };

            tableModel.addRow(row);
        }

        // 刷新表格显示
        detailTable.revalidate();
        detailTable.repaint();
        System.out.println("=== 成绩详情加载完成 ===");
    }

    private String getCorrectAnswer(Question question) {
        if (question.isChoiceQuestion() && question.getOptions() != null) {
            StringBuilder correct = new StringBuilder();
            for (QuestionOption option : question.getOptions()) {
                if (option.isCorrect()) {
                    if (correct.length() > 0)
                        correct.append(", ");
                    correct.append(option.getOptionLabel()).append(". ").append(option.getOptionText());
                }
            }
            return correct.toString();
        } else if (question.isTrueFalseQuestion()) {
            String correctAnswer = question.getCorrectAnswer();
            if (correctAnswer != null) {
                return "true".equals(correctAnswer) ? "正确 (True)" : "错误 (False)";
            }
            return "未设置正确答案";
        } else if (question.isFillBlankQuestion()) {
            String correctAnswer = question.getCorrectAnswer();
            return correctAnswer != null ? correctAnswer : "未设置标准答案";
        } else {
            return "需要教师评分";
        }
    }

    private String getQuestionTypeText(String type) {
        switch (type) {
            case "single_choice":
                return "单选题";
            case "multiple_choice":
                return "多选题";
            case "true_false":
                return "判断题";
            case "fill_blank":
                return "填空题";
            case "essay":
                return "问答题";
            default:
                return type;
        }
    }
}